/*
 * Copyright (C) 2009 Leandro Aparecido <lehphyro@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.metalframework.persistence.repository.query.loader.jpa;

import java.util.*;

import javax.persistence.*;

import org.metalframework.persistence.repository.*;
import org.springframework.orm.jpa.*;


/**
 * Callback of JPA queries to interact with the EntityManager directly.
 * 
 * @since 1.0
 * @see org.springframework.orm.jpa.JpaCallback
 */
public class JpaQueryCallback<V> implements JpaCallback<List<V>> {
	/**
	 * Name of the query to execute.
	 */
	private String queryName;
	
	/**
	 * All possible parameters of the query.
	 */
	private Map<String, QueryParameter> parameters;

	/**
	 * Creates the callback with the specified parameters.
	 * 
	 * @param queryName Name of the query to execute.
	 * @param parameters All possible parameters of the query.
	 */
	public JpaQueryCallback(String queryName, Map<String, QueryParameter> parameters) {
		this.queryName = queryName;
		this.parameters = parameters;
	}
	
	/**
	 * {@inheritDoc}
	 */
	@SuppressWarnings("unchecked")
	public List<V> doInJpa(EntityManager em) throws PersistenceException {
		Query queryObject = em.createNamedQuery(queryName);
		if (parameters != null) {
			for (Map.Entry<String, QueryParameter> entry : parameters.entrySet()) {
				try {
					queryObject.setParameter(entry.getKey(), entry.getValue().getActualValue());
				} catch (IllegalArgumentException e) {
					// The parameter is not expected, just ignore it
				}
			}
		}
		return queryObject.getResultList();
	}
	
}
